/**
 * Classname :WebUserDetailsService.java
 *
 * Version information: 1.0
 *
 * Date: Dec 14, 2011 ho.viet.duan create
 *
 * MDG Viet Name co.ltd, All Rights Reserved.
 */
package com.zho.web.security;

import com.zho.business.AccountManager;
import com.zho.common.Constants.Role;
import com.zho.common.utility.Constants.Active;
import com.zho.domain.model.CustomerInfo;
import com.zho.util.Logit;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
*
* @author Ho.Viet.Duan	
* Created Jan 07, 2011
*/
public class WebUserDetailsService implements IWebUserDetailsService, InitializingBean {
    Logit log = Logit.getInstance(WebUserDetailsService.class);

	AccountManager accountManager = null;

	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
	
	/*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
	public synchronized UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
    	final String LOCATION = "loadUserByUsername(userName:" + userName + ")";
    	 log.debug(LOCATION + ":: START");
    		WebUserDetails user = null;
    		CustomerInfo customerInfo = null;
    	try {
   			customerInfo = accountManager.getCustomerByEmail(userName);
    		if (customerInfo == null || Active.INACTIVE.equals(customerInfo.getActiveFlg())) {        			
                log.info("User not found!!!");
    			throw new UsernameNotFoundException("User not found!!!");
            }
    		user = new AppWebUserDetails(customerInfo, Role.MEMBER);
    		
        } catch (UsernameNotFoundException ufe) {
        	log.error(ufe.getMessage(), ufe);
            throw ufe;
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
            throw new UsernameNotFoundException("User not found!!!", e);
        }
        log.debug(LOCATION + ":: END");
        return user;
    }

    /*
     * (non-Javadoc)
     * 
     * @see kr.ac.edu.lab.web.security.IWebUserDetailsService#reloadUserByUsername(java.lang.String)
     */
    public void reloadUserByUsername(String userName) {

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
    }
}
